<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of AuthController
 *
 * @author dung
 */
class AuthController extends BaseController
{
    //put your code here

    /**
     * generate signup form
     * @return View
     */
    public function getSignUp()
    {
        // is the user logged in?
        if (Sentry::check()) {
            return Redirect::route('account');
        }

        //show the page
        return View::make('frontend.auth.signup', $this->data);
    }

    /**
     * process sign up
     * @return Redirect
     */
    public function postSignUp()
    {
        $rules = array(
            'username' => 'required|alpha_dash|unique:users,username|min:4',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|between:8,32',
            'confirm_password' => 'required|same:password',
            'agree' => 'required'
        );
        $validator = Validator::make(Input::all(), $rules);
        if ($validator->fails())
            return Redirect::back()->withInput()->withErrors($validator);

        try {
            // Register the user
            $user = Sentry::register(array(
                'username' => Input::get('username'),
                'first_name' => Input::get('first_name'),
                'email' => Input::get('email'),
                'password' => Input::get('password'),
                'activated' => 1,
            ));

            // Find the group using the group id
            $memberGroup = Sentry::findGroupById(Config::get('constants.MEMBER_GROUP'));
            // Assign the group to the user
            $user->addGroup($memberGroup);

            // Data to be used on the email view
            $data = array(
                'title' => '',
                'user' => $user,
                'activationUrl' => URL::route('activate', $user->getActivationCode()),
                'type' => 'register-activate'
            );

            // send mail
            Mailer::sendmail($data);

            // Redirect to the register page
            return Redirect::route('signin')->with('success', Lang::get('auth/message.signup.success'));
        } catch (Cartalyst\Sentry\Users\UserExistsException $e) {
            $this->messageBag->add('email', Lang::get('auth/message.account_already_exists'));
        }

        // Ooops.. something went wrong
        return Redirect::back()->withInput()->withErrors($this->messageBag);
    }

    /**
     * User account activation page.
     *
     * @param  string $actvationCode
     * @return
     */
    public function getActivate($activationCode = null)
    {
        // Is the user logged in?
        if (Sentry::check()) {
            return Redirect::route('account');
        }
        try {
            // Get the user we are trying to activate
            $user = Sentry::getUserProvider()->findByActivationCode($activationCode);

            // Try to activate this user account
            if ($user->attemptActivation($activationCode)) {
                // Redirect to the login page
                return Redirect::route('signin')->with('success', Lang::get('auth/message.activate.success'));
            }

            // The activation failed.
            $error = Lang::get('auth/message.activate.error');
        } catch (Cartalyst\Sentry\Users\UserNotFoundException $e) {
            $error = Lang::get('auth/message.activate.error');
        }

        // Ooops.. something went wrong
        return Redirect::route('signin')->with('error', $error);
    }

    /**
     * generate form signin
     * @return View
     */
    public function getSignIn()
    {
        if (Sentry::check()) {
            return Redirect::route('account');
        }
        return View::make('frontend.auth.signin');
    }

    /**
     * process sign in
     * return Redirect
     */
    public function postSignIn()
    {
        // Declare the rules for the form validation
        $rules = array(
            'username' => 'required',
            'password' => 'required'
        );
        // Create a new validator instance from our validation rules
        $validator = Validator::make(Input::all(), $rules);
        // If validation fails, we'll exit the operation now.
        if ($validator->fails()) {
            // Ooops.. something went wrong
            return Redirect::back()->withInput()->withErrors($validator);
        }
        try {
            // Try to log the user in
            Sentry::authenticate(Input::only('username', 'password', 'md5password', 'md5password_utf'), Input::get('remember-me', 0));

            // Get the page we were before
            $redirect = Session::get('loginRedirect', '/');

            // Unset the page we were before from the session
            Session::forget('loginRedirect');

            // Redirect to the users page
            return Redirect::to($redirect)->with('success', Lang::get('auth/message.signin.success'));
        } catch (Cartalyst\Sentry\Users\UserNotFoundException $e) {
            $this->messageBag->add('email', Lang::get('auth/message.account_not_found'));
        } catch (Cartalyst\Sentry\Users\UserNotActivatedException $e) {
            $this->messageBag->add('email', Lang::get('auth/message.account_not_activated'));
        } catch (Cartalyst\Sentry\Throttling\UserSuspendedException $e) {
            $this->messageBag->add('email', Lang::get('auth/message.account_suspended'));
        } catch (Cartalyst\Sentry\Throttling\UserBannedException $e) {
            $this->messageBag->add('email', Lang::get('auth/message.account_banned'));
        }

        // Ooops.. something went wrong
        return Redirect::back()->withInput()->withErrors($this->messageBag);
    }

    public function postAjaxSignIn()
    {
        if (Request::ajax()) {
            $rules = array(
                'username' => 'required',
                'password' => 'required'
            );
            $validation = Validator::make(Input::all(), $rules);
            if ($validation->fails()) {
                return Response::json($validation);
            }
            try {
                // Try to log the user in
                Sentry::authenticate(Input::only('username', 'password', 'md5password', 'md5password_utf'), Input::get('remember-me', 0));

                // Get the page we were before
                $redirect = Session::get('loginRedirect', '/');

                // Unset the page we were before from the session
                Session::forget('loginRedirect');

                // Redirect to the users page
//                return Redirect::to($redirect)->with('success', Lang::get('auth/message.signin.success'));
                return Response::json(array('success' => true));
            } catch (Cartalyst\Sentry\Users\UserNotFoundException $e) {
                $this->messageBag->add('email', Lang::get('auth/message.account_not_found'));
            } catch (Cartalyst\Sentry\Users\UserNotActivatedException $e) {
                $this->messageBag->add('email', Lang::get('auth/message.account_not_activated'));
            } catch (Cartalyst\Sentry\Throttling\UserSuspendedException $e) {
                $this->messageBag->add('email', Lang::get('auth/message.account_suspended'));
            } catch (Cartalyst\Sentry\Throttling\UserBannedException $e) {
                $this->messageBag->add('email', Lang::get('auth/message.account_banned'));
            }
            return Response::json($this->messageBag);
        }
    }

    /**
     * Forgot password page
     * @return View
     */
    public function getForgotPassword()
    {
        if (Sentry::check())
            return Redirect::route('account');
        return View::make('frontend.auth.forgot-password', $this->data);
    }

    /**
     * process forgot password
     * @return View
     */
    public function postForgotPassword()
    {
        $email = Jinput::get('email');
        $rules = array('email' => 'required|email|exists:users');

        $validation = Validator::make(Input::all(), $rules);

        if ($validation->fails())
            return Redirect::back()->withInput()->withErrors($validation);

        try {
            $user = Sentry::getUserProvider()->getEmptyUser();
            $user = $user->where('email', '=', $email)->first();
            // Data to be used on the email view
            $data = array(
                'title' => '',
                'user' => $user,
                'type' => 'forgot-password',
                'forgotPasswordUrl' => URL::route('forgot-password-confirm', $user->getResetPasswordCode()),
            );
            Mailer::sendMail($data);
        } catch (Cartalyst\Sentry\Users\UserNotFoundException $e) {
            return Redirect::route('forgot-password')->with('error', Lang::get('auth/message.account_not_found'));
        }
        //  Redirect to the forgot password
        return Redirect::route('forgot-password')->with('success', Lang::get('auth/message.forgot-password.success'));
    }

    /**
     * Forgot Password Confirmation page.
     *
     * @param  string $passwordResetCode
     * @return View
     */
    public function getForgotPasswordConfirm($passwordResetCode = null)
    {
        try {
            // Find the user using the password reset code
            $user = Sentry::getUserProvider()->findByResetPasswordCode($passwordResetCode);
        } catch (Cartalyst\Sentry\Users\UserNotFoundException $e) {
            // Redirect to the forgot password page
            return Redirect::route('forgot-password')->with('error', Lang::get('auth/message.account_not_found'));
        }

        // Show the page
        return View::make('frontend.auth.forgot-password-confirm', $this->data);
    }

    /**
     * Forgot Password Confirmation form processing page.
     *
     * @param  string $passwordResetCode
     * @return Redirect
     */
    public function postForgotPasswordConfirm($passwordResetCode = null)
    {
        // Declare the rules for the form validation
        $rules = array(
            'password' => 'required',
            'password_confirm' => 'required|same:password'
        );
    }


    /**
     * Logout page.
     *
     * @return Redirect
     */
    public function getLogout()
    {
        // Log the user out
        Sentry::logout();

        // Redirect to the users page
        return Redirect::route('home')->with('success', 'You have successfully logged out!');
    }

}
